import axios from 'axios'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_PATH,
  timeout: 10000,
  withCredentials: true,
})

request.interceptors.request.use(
  (config) => {
    Object.assign(config.headers, {})

    return Promise.resolve(config)
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    const { status, data } = response

    if (+status !== 200) {
      return Promise.reject(response?.data ?? {})
    }

    if (data?.code !== 200 || !data?.success) {
      return Promise.reject(response?.data ?? {})
    }

    return Promise.resolve(data)
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default request
